package cn.ywang.listener;

import cn.ywang.EnumType;
import cn.ywang.event.Event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author BeatificWang
 * @date 2019/1/1 17:53
 */
public class EventListener {
	/**
	 * 监听器
	 */
	Map<Enum, Event> listeners = new HashMap<>();

	/**
	 * 添加监听器
	 *
	 * @param type     监听事件类型
	 * @param target   观察者
	 * @param callBack 回调方法
	 */
	public void addListener(EnumType type, Object target, Method callBack) {
		if (!this.listeners.containsKey(type)) {
			Event event = new Event(target, callBack);
			event.setSource(this);
			this.listeners.put(type, event);
		}
	}

	protected void trigger(EnumType type) {
		if (this.listeners.containsKey(type)) {
			Event event = this.listeners.get(type);
			event.setTrigger(type.toString());
			event.setTime(System.currentTimeMillis());
			try {
				event.getCallBack().invoke(event.getTarget(), event);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}
